<template>
  <div class="sub-content-box" v-loading="loading">
    <div class="chart-box" v-for="item in pieTypeList" :key="item.dictCode">
      <Pie :loading="item.loading" :chartData="item.chartData"
        :title="`${item.itemName}占比分析`" />
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import Pie from '@/components/Charts/Pie/index.vue'
import { getchildDataLengRePie, } from '@/api/common/chart'
import { getDictListByCode } from '@/api/sys/dict'

const props = defineProps({
  searchInfo: {
    type: Object,
    default: () => ({}),
  }
})

const dictCode = 'LengRePie'
const pieTypeList = ref([])
const dataReady = ref(false)

// 保存当前搜索参数的副本
const currentSearchParams = ref({})

// 暴露给父组件调用的搜索方法
const handleSearch = async (params = {}) => {
  console.log('子组件接收到搜索参数', params)

  // 合并新参数和当前参数
  currentSearchParams.value = {
    ...currentSearchParams.value,
    queryType: params.queryType,
    startDay: params.startDay,
    endDay: params.endDay
  }

  // 如果类型列表还没准备好，先获取类型列表
  if (!dataReady.value) {
    await getTypeList()
  }

  // 使用合并后的参数获取图表数据
  getPieChartData(currentSearchParams.value)
}

onMounted(async () => {
  await getTypeList()
  // 初始化时执行一次搜索，使用初始props中的参数
  handleSearch(props.searchInfo)
})

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode)
  dataReady.value = true
  pieTypeList.value = res.map((item) => ({
    ...item,
    loading: true,
    chartData: [],
  }))
}

const getPieChartData = (searchInfo) => {
  console.log('获取图表数据的参数:', searchInfo)

  pieTypeList.value.forEach((item) => {
    item.loading = true
    getchildDataLengRePie({
      ...searchInfo,
      dictCode:item.itemCode,
    })
      .then((res) => {
        res.forEach(item => {
          item.label = {
            formatter: function (data) {
              return `${data.name} (${data.percent.toFixed(0)}%)`
            }
          }
        })
        item.chartData = res
      })
      .finally(() => {
        item.loading = false
      })
  })
}

// watch(
//   () => props.searchInfo,
//   (newValue) => {
//     console.log('搜索参数变化:', newValue)
//     if (Object.values(newValue).length > 0) {
//       handleSearch(newValue)
//     }
//   },
//   { immediate: false }
// )

// 显式暴露方法给父组件
defineExpose({
  handleSearch
})
</script>
<style scoped lang="scss">
.sub-content-box {
  display: flex;
  flex-wrap: wrap;
  height: 100%;
  gap: 8px;
  overflow: auto;

  .chart-box {
    width: calc(50% - 8px);
    height: 32%;
    padding: 4px;
    box-sizing: border-box;
  }
}
</style>
